<template>
  <div>
    <Breadcrumbs :breadtitle="{ '1': '商品管理', '2': '商品参数' }"></Breadcrumbs>
    <!-- 卡片 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon>
      </el-alert>
      <!-- 选择器 -->
      <el-form ref="form" label-width="120px">
        <el-form-item label="选择商品分类：">
          <el-cascader expand-trigger="hover" clearable :options="CategoriesList" :props="cascaderProps" v-model="selectKeys" @change="handleTabClick"></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">

        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many" :disabled="isBtnDisabled">
          <!-- 添加按钮 -->
          <el-row :gutter="20" type="flex" justify="end">
            <el-col :span="2" :pull="1">
              <el-button @click="diaParams = true;Btntype=0" :disabled="isBtnDisabled">添加参数</el-button>
            </el-col>
          </el-row>
          <!-- 表格 -->
          <el-table :data="ShowRolesList[pagenum]" border style="width: 100%" stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">

                <!-- 标签 -->
                <el-tag style="marginRight:10px" closable v-for="(item,index) in vals(scope.row.attr_vals)" :key=index @close="DelTag(vals(scope.row.attr_vals),scope.row,index)">{{item}}</el-tag>

                <!-- 添加新的标签 -->
                <el-input class="input-new-tag" v-if="inputVisId==scope.row.attr_id" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="SetParams(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="DelParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态参数 -->
        <el-tab-pane label="静态参数" name="only" :disabled="isBtnDisabled">
          <!-- 添加按钮 -->
          <el-row :gutter="20" type="flex" justify="end">
            <el-col :span="2" :pull="1">
              <el-button @click="diaParams = true;Btntype=0" :disabled="isBtnDisabled">添加属性</el-button>
            </el-col>
          </el-row>

          <el-table :data="ShowRolesList[pagenum]" border style="width: 100%" stripe>

            <el-table-column type="expand">
              <template slot-scope="scope">

                <!-- 标签 -->
                <el-tag style="marginRight:10px" closable v-for="(item,index) in vals(scope.row.attr_vals)" :key=index @close="DelTag(vals(scope.row.attr_vals),scope.row,index)">{{item}}</el-tag>
                <!-- 添加新的标签 -->
                <el-input class="input-new-tag" v-if="inputVisId==scope.row.attr_id" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>

            <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="SetParams(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="DelParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 分页 -->
        <el-pagination v-if="!isBtnDisabled" :current-page="pagenum" :page-size="7" :total="total" layout="total, prev, pager, next, jumper" @current-change="handleCurrentChange">
        </el-pagination>
      </el-tabs>

      <el-dialog :title="activeName=='many'?'添加参数':'添加属性'" :visible.sync="diaParams" @close="close" width="45%">

        <!-- 主体 -->
        <el-form ref="form" label-width="80px">
          <el-form-item required :label="activeName=='many'?'动态参数':'静态属性'">
            <el-input v-model="attr_name"></el-input>
          </el-form-item>
        </el-form>

        <!-- 按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="diaParams=false">取消</el-button>
          <el-button type="primary" @click="BtnPostParams">
            提交
          </el-button>
        </span>
      </el-dialog>
    </el-card>

  </div>
</template>

<script>
import Breadcrumbs from '@/components/Breadcrumbs'
export default {
  name: 'Params',
  data() {
    return {
      CategoriesList: null,
      ParamsList: null,
      ShowRolesList: {},
      selectKeys: [],
      diaParams: false,
      inputValue: '',
      inputVisId: null,
      Btntype: null,  //判断是添加还是编辑
      attr_id: null,
      attr_vals: null,
      activeName: 'many',
      attr_name: '',
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      pagenum: 1, //当前的页数
      total: null
    }
  },
  computed: {
    isBtnDisabled() {   //如果按钮需要被禁用,则true,否认为false
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },
    vals() {
      return (val) => {
        if (val.length > 0) {
          return val.split(' ')
        }
        return null
      }
    }
  },
  components: {
    Breadcrumbs
  },
  created() {
    this.getCategories()
  },
  methods: {
    getCategories() {  //获取分类列表
      this.$http.get('categories').then(res => {
        if (res.data.meta.status !== 200) return
        this.CategoriesList = res.data.data
      })
    },
    getParams() {  //获取参数列表
      this.$http.get(`categories/${this.selectKeys[2]}/attributes`, { params: { sel: this.activeName } }).then(res => {
        if (res.data.meta.status !== 200) {
          this.$mess(res.data.meta.msg, 'error')

          return
        }
        this.ParamsList = res.data.data
        this.total = res.data.data.length //总页数
        this.ShowRolesList = {}
        for (var i = 0; i < Math.ceil(this.total / 7); i++) { //处理成每个7个数据
          let num = 7 * (i + 1)
          if (num > this.total) num = this.total
          this.ShowRolesList[i + 1] = this.ParamsList.slice(7 * (i), num)
        }
        this.attr_vals = res.data.data.attr_vals
      })
    },
    handleTabClick() {  //级联选择器
      if (this.selectKeys.length == 3) {
        this.getParams()
        this.pagenum = 1
      } else {
        this.ShowRolesList = {}
        this.ParamsList = null
      }
    },
    handleClick() {    //标签页
      this.getParams()
      this.pagenum = 1
    },
    close() {  //监听关闭弹窗
      this.attr_name = ''
      this.attr_id = ''
    },
    BtnPostParams() {  //提交按钮
      if (this.Btntype == 0) { //是添加
        this.$http.post(`categories/${this.selectKeys[2]}/attributes`, { attr_name: this.attr_name, attr_sel: this.activeName }).then(res => {
          if (res.data.meta.status !== 201) {
            this.$mess(res.data.meta.msg, 'error')
            return
          }
          this.$mess(res.data.meta.msg, 'success')
          this.getParams()
          this.diaParams = false;
        })
      } else if (this.Btntype == 1) {  //是编辑
        this.$http.put(`categories/${this.selectKeys[2]}/attributes/${this.attr_id}`, { attr_name: this.attr_name, attr_sel: this.activeName }).then(res => {
          if (res.data.meta.status !== 200) {
            this.$mess(res.data.meta.msg, 'error')
            return
          }
          this.$mess(res.data.meta.msg, 'success')
          this.getParams()
          this.diaParams = false;
        })
      }
    },
    SetParams(item) {  //编辑按钮
      this.Btntype = 1
      this.diaParams = true;
      this.attr_name = item.attr_name
      this.attr_id = item.attr_id
    },
    DelParams(Id) {  //删除按钮
      this.$confirm('此操作将永久删除该账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http.delete(`categories/${this.selectKeys[2]}/attributes/${Id}`).then(res => {
            if (res.data.meta.status !== 200) {
              this.$mess(res.data.meta.msg, 'error')
              return
            }
            this.$mess(res.data.meta.msg, 'success')
            this.getParams()
          })
        })
        .catch(() => {
          this.$mess('已取消删除', 'info')
        })

    },

    handleInputConfirm(item) {  //本文框失去焦点
      if (this.inputValue.replace(/\s/g, '').length > 0) {
        let attr_vals = ''
        if (item.attr_vals.length == ' ') {
          attr_vals = this.inputValue.replace(/\s/g, '')
          item.attr_vals = attr_vals
        } else {
          attr_vals = item.attr_vals + ' ' + this.inputValue.replace(/\s/g, '')
          item.attr_vals = attr_vals
        }

        this.$http.put(`categories/${this.selectKeys[2]}/attributes/${this.attr_id}`, { attr_name: item.attr_name, attr_sel: this.activeName, attr_vals: attr_vals }).then(res => {
          if (res.data.meta.status !== 200) {
            this.$mess(res.data.meta.msg, 'error')
            return
          }
          this.$mess(res.data.meta.msg, 'success')
          this.inputValue = ''
          this.inputVisId = null

        })
      } else {
        this.inputValue = ''
        this.inputVisId = null
      }

    },

    showInput(item) {  //新建标签按钮
      this.inputVisId = item.attr_id
      this.attr_id = item.attr_id
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    DelTag(arr, item, i) {  //删除标签
      arr.splice(i, 1)
      let str = arr.join().replace(/,/g, ' ')
      this.$http.put(`categories/${this.selectKeys[2]}/attributes/${item.attr_id}`, { attr_name: item.attr_name, attr_sel: this.activeName, attr_vals: str }).then(res => {
        if (res.data.meta.status !== 200) {
          this.$mess(res.data.meta.msg, 'error')
          return
        }
        this.inputValue = ''
        this.inputVisId = null
        item.attr_vals = str
      })
    },
    handleCurrentChange(newNum) {   //监听 页码值 改变事件
      this.pagenum = newNum
      this.getParams()
    },
  }
}
</script>

<style>
.input-new-tag {
  width: 90px;
}
</style>